package cn.edu.fzu.homemaking.aop;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Component
@Aspect
public class RequestLogAdvice {

    Logger logger = LoggerFactory.getLogger(RequestLogAdvice.class);

    /**
     * 切入点
     */
    @Pointcut("@annotation(cn.edu.fzu.homemaking.annotation.LogAop)")
    public void logAop() {
    }


    /**
     * 请求日志
     */
    @Around("logAop()")
    public Object arround(ProceedingJoinPoint joinPoint) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        Signature signature = joinPoint.getSignature();
        logger.info("==================================== REQUEST ========================================");
        logger.info("url：{} {}", request.getMethod(), request.getRequestURL().toString());
        logger.info("method：{}.{}", signature.getDeclaringTypeName(), signature.getName());
        logger.info("IP：{}", request.getRemoteAddr());
        Object result = joinPoint.proceed();
        logger.info("====================================== END ==========================================");
        return result;
    }
}
